//
//  ColloquiumViewController.m
//  CoMeT
//
//  Created by Gang on 6/14/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ColloquiumViewController.h"
#import "CoMeTAppDelegate.h"
#import "LoginViewController.h"
#import "CoMeTAPI.h"
#import "NetUtil.h"


@implementation ColloquiumViewController
@synthesize mytableView;
@synthesize talk;

@synthesize talkTitle;
@synthesize authorDetail;
@synthesize location;
@synthesize time;
@synthesize viewCount;
@synthesize bookmarkCount;
@synthesize bookmarkBtn;
@synthesize bookmarked;

-(void) bookmark:(NSString *)cid{
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    if ([NetUtil checkNetworkStatus:nil]== 0 ) {
        UIAlertView *alertfailure = [[UIAlertView alloc] initWithTitle:@"Error" message:@"No Network Connection! Please open your wifi or wwan connection"
                                                              delegate:self cancelButtonTitle:@"Return" otherButtonTitles:nil, nil];
        [alertfailure show];
        [alertfailure release];
        
        return;
        
    }
    NSLog(@"Network is OK");
    
    NSString *postSchedule =[NSString stringWithFormat:@"user_id=%@&col_id=%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"userid"],cid];
    NSString *hostStrSchedule = @"http://halley.exp.sis.pitt.edu/comet/utils/addBookmarkXML.jsp?";
    hostStrSchedule = [hostStrSchedule stringByAppendingString:postSchedule];
    
    NSURL *urlSchedule=[[NSURL alloc] initWithString:hostStrSchedule];
    
    NSMutableURLRequest *urlRequestSch=[NSMutableURLRequest requestWithURL:urlSchedule];
    [urlSchedule release];
    
    //[urlRequestSch setHTTPMethod:@"POST"];
    //[urlRequestSch setHTTPBody:[postSchedule dataUsingEncoding:NSASCIIStringEncoding]];
    //[urlRequestSch setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSLog(@"Ready to sendf Request");
    
    NSURLResponse *responseSch;
    NSError *errorSch;
    NSData *aDataSch = [NSURLConnection sendSynchronousRequest:urlRequestSch returningResponse:&responseSch error:&errorSch];
    NSString *serverOutputSch = [[NSString alloc] initWithData:aDataSch encoding: NSUTF8StringEncoding];
    
    NSLog(@"Response received");
    [serverOutputSch release];
    [pool release];
    
}


-(void) unBookmark:(NSString *)cid{
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    if ([NetUtil checkNetworkStatus:nil]== 0 ) {
        UIAlertView *alertfailure = [[UIAlertView alloc] initWithTitle:@"Error" message:@"No Network Connection! Please open your wifi or wwan connection"
                                                              delegate:self cancelButtonTitle:@"Return" otherButtonTitles:nil, nil];
        [alertfailure show];
        [alertfailure release];
        
        return;
        
    }
    NSString *postSchedule =[NSString stringWithFormat:@"user_id=%@&col_id=%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"userid"],cid];
    NSString *hostStrSchedule = @"http://halley.exp.sis.pitt.edu/comet/utils/removeBookmarkXML.jsp?";
    hostStrSchedule = [hostStrSchedule stringByAppendingString:postSchedule];
    
    NSURL *urlSchedule=[[NSURL alloc] initWithString:hostStrSchedule];
    
    NSMutableURLRequest *urlRequestSch=[NSMutableURLRequest requestWithURL:urlSchedule];
    [urlSchedule release];
    
    [urlRequestSch setHTTPMethod:@"POST"];
    [urlRequestSch setHTTPBody:[postSchedule dataUsingEncoding:NSASCIIStringEncoding]];
    [urlRequestSch setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    
    NSURLResponse *responseSch;
    NSError *errorSch;
    NSData *aDataSch = [NSURLConnection sendSynchronousRequest:urlRequestSch returningResponse:&responseSch error:&errorSch];
    NSString *serverOutputSch = [[NSString alloc] initWithData:aDataSch encoding: NSUTF8StringEncoding];
    
    
    [serverOutputSch release];
    [pool release];
}




- (CGFloat) cellHeightForText:(NSString *) text{
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:14.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [text sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    
    return labelSize.height + 10;
}




// table delegation

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return  2;
    
}


// Customize the appearance of table view cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    }
    
    if (indexPath.row ==0) {
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.textLabel.numberOfLines = 0;  
        cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:14.0];
        cell.textLabel.text = detailText;
    }else{
        cell.textLabel.text = [NSString stringWithFormat: @"Posted By: %@", [self.talk objectForKey:@"owner"]];
        
    }
    
    return cell;
    
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    
    return @"Detail";
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row ==0) {
        NSString *string = nil;
        string = detailText;
        
        return [self cellHeightForText:string] ;
    }else{
        return 24.0f;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
        
    
    self.talkTitle.text = [self.talk objectForKey:@"title"];
    self.authorDetail.text =[self.talk objectForKey:@"detail"];
    
    self.viewCount.text =[self.talk objectForKey:@"viewCount"];
    self.bookmarkCount.text = [self.talk objectForKey:@"bookmarkCount"];
    self.location.text = [self.talk objectForKey:@"location"];
    self.time.text = [NSString stringWithFormat:@"%@ %@-%@",[self.talk objectForKey:@"date"],[self.talk objectForKey:@"begintime"],[self.talk objectForKey:@"endtime"]];
    
    // Set the custom back button
    
    UIImage *buttonImage = [UIImage imageNamed:@"br_prev.png"];
    
    //create the button and assign the image
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [button setImage:buttonImage forState:UIControlStateNormal];
    //set the frame of the button to the size of the image (see note below)
    
    button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
    
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    //create a UIBarButtonItem with the button as a custom view
    
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.leftBarButtonItem = customBarItem;
    [customBarItem release];

    
    
    
    NSString *detailURL = [NSString stringWithFormat: @"http://halley.exp.sis.pitt.edu/comet/colloquia/presentDetail.jsp?cleantxt=1&col_id=%@", [self.talk objectForKey:@"id"] ];
    
    NSString *returnData;
	@try {
        NSString *urlString = detailURL;
        NSString *agentString = @"iPhone App";
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: 
                                        [NSURL URLWithString:urlString]];
        [request setValue:agentString forHTTPHeaderField:@"User-Agent"];
        NSData *data = [ NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
        
        returnData = [[NSString alloc] initWithBytes: [data bytes] length:[data length] encoding: NSUTF8StringEncoding];
        ////NSLog(@"Inside loadDetail() %@", returnData);
	}
	@catch (NSException* ex) {
		//NSLog(@"loadDetail failed: %@",ex);
		returnData = @"No details for this talk";
	}
	@finally {
		detailText = returnData;
	}
    
    
    CoMeTAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
	
	
	//if([self.talk.status isEqualToString:@"0"])
	if (![appDelegate isBookmarked:[self.talk objectForKey:@"id"]])
	{

        [self.bookmarkBtn setTitle:@"Add Bookmark" forState:UIControlStateNormal];
        [self.bookmarkBtn setTitle:@"Add Bookmark" forState:UIControlStateHighlighted];
        [self.bookmarkBtn setImage:[UIImage imageNamed:@"calendar_add_15.png"] forState:UIControlStateNormal];
        [self.bookmarkBtn setImage:[UIImage imageNamed:@"calendar_add_15.png"] forState:UIControlStateHighlighted];
		
	}
	else {
		[self.bookmarkBtn setTitle:@"Remove Bookmark" forState:UIControlStateNormal];
		[self.bookmarkBtn setTitle:@"Remove Bookmark" forState:UIControlStateHighlighted];
        [self.bookmarkBtn setImage:[UIImage imageNamed:@"calendar_delete_15.png"] forState:UIControlStateNormal];
        [self.bookmarkBtn setImage:[UIImage imageNamed:@"calendar_delete_15.png"] forState:UIControlStateHighlighted];
	}
    
}

-(void)back {
    // Tell the controller to go back
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction) updateStatus:(id) sender{
    CoMeTAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
	
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    if (![[prefs valueForKey:@"authorized"] isEqualToString:@"yes" ]) {
        LoginViewController *loginView = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginView animated:YES];
        [loginView release];
    }
    

	if ([appDelegate isBookmarked:[self.talk objectForKey:@"id"]])
	{
        
    
        //[CoMeTAPI unBookmark:[self.talk objectForKey:@"id"]];
        [self performSelectorInBackground:@selector(unBookmark:) withObject:nil];
		[self.bookmarkBtn setTitle:@"Add Bookmark" forState:UIControlStateNormal];
		[self.bookmarkBtn setTitle:@"Add Bookmark" forState:UIControlStateHighlighted];
        [self.bookmarkBtn setImage:[UIImage imageNamed:@"calendar_add_15.png"] forState:UIControlStateNormal];
        [self.bookmarkBtn setImage:[UIImage imageNamed:@"calendar_add_15.png"] forState:UIControlStateHighlighted];
		[appDelegate.bookmarks removeObject:self.talk];
    }
    
    else 
    
    {
       //[CoMeTAPI bookmark:[self.talk objectForKey:@"id"]];
        [self performSelectorInBackground:@selector(bookmark:) withObject:nil];
		[self.bookmarkBtn setTitle:@"Remove Bookmark" forState:UIControlStateNormal];
		[self.bookmarkBtn setTitle:@"Remove Bookmark" forState:UIControlStateHighlighted];
		[appDelegate.bookmarks addObject:self.talk];
        [self.bookmarkBtn setImage:[UIImage imageNamed:@"calendar_delete_15.png"] forState:UIControlStateNormal];
        [self.bookmarkBtn setImage:[UIImage imageNamed:@"calendar_delete_15.png"] forState:UIControlStateHighlighted];
	
        
            }
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
